<?php

namespace App\Http\Controllers\Login;

use App\Http\Controllers\BaseController;
use App\Libraries\CodeDefine;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;

class LoginController extends BaseController
{

    public function index(Request $request) {
        return view('login.login', $this->view_data);
    }

    /**
     * 接口方式调用登录
     */
    public function api_login(Request $request) {
        $credentials = $request->only('username', 'password');
        if (auth('web')->attempt($credentials, true)) {
            return redirect("/");
        }
        return $this->apiError("登录失败，请检查账号或密码是否错误", 6001, [], '');
    }

    public function login(Request $request) {
        $messages = [
            'username.required' => CodeDefine::$message[CodeDefine::CODE_ERROR_USER], #'Please enter your email',
            'password.required' => CodeDefine::$message[CodeDefine::CODE_ERROR_PASS], #'Please enter your password',
            //'captcha.required' => CodeDefine::$message[CodeDefine::CODE_CAPTCHA_ERR], #'Please enter your code'
        ];

        $validator = Validator::make($request->input(), [
            'password' => 'required|min:3',
            'username' => 'required|min:2',
            //'captcha' => 'required|captcha'
        ], $messages);

        if ($validator->fails()) {
            $error_msg = $validator->errors()->first();
            return $this->apiError($error_msg, CodeDefine::CODE_ERROR_PARAMS);
        }
        $credentials = $request->only('username', 'password');
        if (auth('web')->attempt($credentials, true)) {
            return $this->apiSuccess([],'登录成功', 0, '', 1);
        }
        return $this->apiError("登录失败，请检查账号或密码是否错误", 6001, [], '');
    }

    /**
     * 退出登录操作
     */
    public function logout (Request $request) {
        Auth::guard()->logout();
        $request->session()->invalidate();
        return redirect('/login');
    }
}
